package com.easycarebn.main.fragment;

import java.util.ArrayList;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.easycarebn.main.adapter.SearchResultAdapter;
import com.easycarebn.main.utils.IResult;
import com.easycarebn.main.utils.ItemDr;
import com.easycarebn.main.utils.Utils;
import com.easycarebn.request.controller.ServerController;
import com.easycarebn.request.controller.ServerController.SearchParamBuilder;
import com.easycarebn.request.controller.SuggestNameType;
import com.easycarebn.request.data.DoctorInfo;
import com.easycarebn.request.data.DoctorInfo.Booking;
import com.easycarebn.request.data.DoctorInfoResponse;
import com.easycarebn.request.data.DoctorScheduleResponse;
import com.easycarebn.request.data.UserResponse;
import com.easycarebn.service.location.LocationServiceManager;
import com.easycarebn.service.request.OnRequest;
import com.timbacsi.main.MainActivity;
import com.timbacsi.main.R;

public class FragmentSearchResult extends Fragment implements IResult {

    private View mView;
    private FrameLayout lineTinnhan;
    private static FragmentSearchResult fragment = null;
    private ListView listmessage;
    private View mFooter;
    private LinearLayout lineTitle;
	
    private IResult callIResult;
    private ArrayList<ItemDr> listItemNews;

    private SearchResultAdapter adapter;
    private int mSelectedDoctorId;
    private ItemDr itemDr = null;
    private int mServiceType = -1;
    static final int DOCTOR = SuggestNameType.DOCTOR.getCode();
    static final int CLINIC = SuggestNameType.CLINIC.getCode();
    static final int HOME_SERVICE = SuggestNameType.HOME_SERVICE.getCode();
    private int mPage = 0;
    private int mLastPage = 0;

    private int mSelectedSpin1;
    private int mSelectedSpin2;
    private int mSelectedSpin3;
    private String mSelectedName;
    private SearchParamBuilder mParamBuilder;
	private String mDataBooking;

    public FragmentSearchResult() {
        listItemNews = new ArrayList<ItemDr>();
        mParamBuilder = new SearchParamBuilder();
    }

    public static FragmentSearchResult newInstance(String title) {
        if (fragment == null) {
            fragment = new FragmentSearchResult();
        }
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof IResult) {
            callIResult = (IResult) activity;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_listview, null);
        //

        return mView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    	lineTitle = (LinearLayout) mView.findViewById(R.id.lineTitle);
		lineTitle.setVisibility(View.GONE);
        callIResult.onDisplay(Utils.TASK_CHILD, "");
        listmessage = (ListView) mView.findViewById(R.id.listmessage);
        lineTinnhan = (FrameLayout) mView.findViewById(R.id.lineTinnhan);

        mFooter = getLayoutInflater(savedInstanceState).inflate(R.layout.load_more, null);
        listmessage.addFooterView(mFooter);

        mServiceType = FragmentHome.newInstance().getSelectedSearchType();
        mSelectedSpin1 = FragmentHome.newInstance().getSelectedSpin1();
        mSelectedSpin2 = FragmentHome.newInstance().getSelectedSpin2();
        mSelectedSpin3 = FragmentHome.newInstance().getSelectedSpin3();
        mSelectedName = FragmentHome.newInstance().getSelectedName();
        mParamBuilder.clear();

        if (mServiceType == DOCTOR) {
            Utils.setTitlePage(mView, getResources().getString(R.string.danh_sach_bac_sy));
            mParamBuilder.putSpecility(mSelectedSpin1);
            mParamBuilder.putDetailSpecility(mSelectedSpin2);
        } else if (mServiceType == CLINIC) {
            Utils.setTitlePage(mView, getResources().getString(R.string.danh_sach_phong_kham));
            mParamBuilder.putClinicType(mSelectedSpin1);
        } else {
            Utils.setTitlePage(mView, getResources().getString(R.string.danh_sach_dvtn));
            mParamBuilder.putServicesType(mSelectedSpin1);
        }
        mParamBuilder.putName(mSelectedName);
        // Search by current location
        Log.d("AAAA", "mSpin3: " + mSelectedSpin3);
        if (mSelectedSpin3 == -1) {
            Location location = LocationServiceManager.getInstance(getActivity()).getLocation();
            if (location == null) {
                Utils.showMessage(getActivity(), R.string.khong_lay_duoc_vi_tri_hien_tai);
            } else {
                mParamBuilder.putGeo(location.getLatitude(), location.getLongitude());
            }
        } else {
            mParamBuilder.putCity(mSelectedSpin3);
        }

        adapter = new SearchResultAdapter(getActivity(), listItemNews, this);
        adapter.setSearchType(mServiceType);
        listmessage.setAdapter(adapter);
        listmessage.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSelectedDoctorId = adapter.getItem(position).getInfo().getId();
                itemDr = adapter.getItem(position);
                Bundle data = new Bundle();
                data.putInt(Utils.KEY_DOCTOR_ID, mSelectedDoctorId);
                data.putInt(Utils.KEY_SERVICE_TYPE, mServiceType);
                Utils.intentToDetailt(getActivity(), Utils.DOCTOR_SERVICE_DETAILT, data);
            }

        });

        Button btnLoadmore = (Button) mFooter.findViewById(R.id.btnLoadMore);
        btnLoadmore.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                requestSearch();
            }
        });

        listmessage.invalidate();
        listItemNews.clear();
        mPage = 0;
        mLastPage = 0;
        requestSearch();
    }

    @Override
    public void onDisplay(int code, String arg2) {

        if (adapter == null) {
            return;
        }
        if (code == Utils.SELECT_TIME_BOOKING) {
        	mDataBooking = arg2;
			UserResponse userResponse = Utils.getUserLogin(getActivity());
			if (userResponse == null) {
				Utils.intentToDetailt(getActivity(), Utils.LOGIN_BOOKING);
			} else {
				Utils.gotoBooking(getActivity(), arg2, mServiceType);
			}

            return;
        }

        int position = code;
        final DoctorInfo doctor = adapter.getItem(position).getInfo();
        Booking booking = doctor.getBooking();
        if (booking == null || TextUtils.isEmpty(booking.getNeardate())) {
            // Show dat lich truoc
            Utils.showDatlichtruoc(getActivity(), doctor);
            return;
        }
        // Hien thi lich kham
        MainActivity.mLoadingData.setVisibility(View.VISIBLE);
        ServerController.getInstance(getActivity()).requestSearchDoctorSchedule(doctor.getId(), booking.getNeardate(),
                new OnRequest<DoctorScheduleResponse>() {

                    @Override
                    public void onSuccess(DoctorScheduleResponse data) {

                        MainActivity.mLoadingData.setVisibility(View.GONE);
                        if (data == null || data.getItems() == null || data.getItems().isEmpty()) {
                            Utils.showMessage(getActivity(), R.string.khong_co_lich_kham);
                        } else {
                            Utils.getDialogTimeBook(getActivity(), FragmentSearchResult.this, doctor.getId(), data.getItems(),
                            		data);
                        }
                    }

                    @Override
                    public void onError(int errorCode, String message) {

                        MainActivity.mLoadingData.setVisibility(View.GONE);
                        Utils.showMessage(getActivity(), message);

                    }
                });
    }

    private void requestSearch() {
        MainActivity.mLoadingData.setVisibility(View.VISIBLE);
        Utils.disableEnableControls(false, mFooter);
        ServerController.getInstance(getActivity()).requestSearch(mServiceType, mPage + 1, mParamBuilder,
                new OnRequest<DoctorInfoResponse>() {

                    @Override
                    public void onSuccess(DoctorInfoResponse data) {
                        MainActivity.mLoadingData.setVisibility(View.GONE);
                        Utils.disableEnableControls(true, mFooter);
                        if (data.getItems() == null) {
                            if (listItemNews.size() == 0) {
                            	
                                Utils.onShowMessageNull(getActivity(), mView, getResources()
                                        .getString(R.string.khong_tim_thay_kq));
                            
                            }
                            return;
                        }
                    	lineTitle.setVisibility(View.VISIBLE);
                        mPage = data.getPaging().getCurrentPage();
                        mLastPage = data.getPaging().getLastPage();
                        if (mLastPage > mPage) {
                            mFooter.setVisibility(View.VISIBLE);
                        } else {
                            listmessage.removeFooterView(mFooter);
                        }

                        for (DoctorInfo info : data.getItems()) {
                            ItemDr item = new ItemDr();
                            item.setDatkham(true);
                            item.setInfo(info);
                            listItemNews.add(item);
                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(int errorCode, String message) {
                        if (errorCode == 0&&listItemNews.size() == 0) {
                            Utils.onResumeRequest(getActivity(), mView, new IResult() {
                                @Override
                                public void onDisplay(int arg1, String arg2) {
                                    requestSearch();
                                }
                            });

                        }
                        MainActivity.mLoadingData.setVisibility(View.GONE);
                        Utils.disableEnableControls(true, mFooter);

                    }
                });
    }

    public ArrayList<ItemDr> getListDoctors() {
        return listItemNews;
    }

    public int getSelectedDoctorId() {
        return mSelectedDoctorId;
    }

    public ItemDr getSelectedItemDr() {
        return itemDr;
    }
    public String getmDataBooking() {
		return mDataBooking;
	}
}
